package com.yu.task;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;
//使用拆分和并框架 计算 1+2+3+...+100
public class TaskExample extends RecursiveTask<Long> {

    private int start;
    private int end;
    private long sum;
    private static final int THRESHOLD = 10; // 阈值

    public TaskExample(int start,int end){
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {

        System.out.println("任务" + start + "=========" + end + "累加开始");
        if (end-start<=THRESHOLD){//小于10（设置的阈值） 直接相机
            for (int i = start; i <=end ; i++) {
                sum += i;
            }
        }else {//大于10就用二分法切割
            int middle = (start + end)/2;
            //拆分左边
            TaskExample left = new TaskExample(start, middle);
            TaskExample right = new TaskExample(middle+1,end);

            left.fork();
            right.fork();
             sum = left.join()+right.join();

        }

        return sum;
    }

    public static void main(String[] args) {
        TaskExample taskExample = new TaskExample(1,100);
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Long> submit = forkJoinPool.submit(taskExample);
        try {
            Long result = submit.get();
            System.out.println(result);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            forkJoinPool.shutdown();
        }
    }
}
